package nayasis.common.db.manager.connection;

import java.sql.Connection;
import java.sql.SQLException;

import nayasis.common.exception.unchecked.DatabaseException;
import nayasis.common.log.NLogger;

/**
 * Connection Pool 이름을 가지고 있는 Wrapper 클래스
 * 
 * @author nayasis
 */
public class WrapperConnection {
	
	private Connection connection = null;
	private String     dbSpec     = null;
	
	/**
	 * 생성자
	 * 
	 * @param connection DB Connection
	 * @param dbSpec DB Spec
	 */
	public WrapperConnection( Connection connection, String dbSpec ) {
		this.connection = connection;
		this.dbSpec = dbSpec;
		try {
			this.connection.setAutoCommit( false );
		} catch ( SQLException e ) {
			throw new DatabaseException( e, "Fail to set autoCommitFalse (@)", dbSpec );
		}
	}
	
	/**
	 * DB Connection을 가져온다.
	 * 
	 * @return DB Connection
	 */
	public Connection getRealConnection() {
		return this.connection;
	}
	
	/**
	 * DB Spec을 가져온다.
	 * 
	 * @return DB Spec
	 */
	public String getDbSpec() {
		return this.dbSpec;
	}
	
	/**
	 * Connnection이 정상적으로 연결되어있는지 확인한다.
	 * 
	 * @return
	 */
	public boolean isValid() {

		if( connection == null ) return false;
		
		try {
			return ! connection.isClosed();
		} catch ( SQLException e ) {
			NLogger.err.println( e );
			close();
			return false;
		}
	}
	
	/**
	 * Connection을 닫는다.
	 */
	public void close() {
		
		if( connection == null ) return;
		
		try {
			connection.close();
		} catch ( SQLException e ) {}
		
		connection = null;
		
	}

	/**
	 * commit 한다.
	 */
	public void commit() {

		if( connection == null ) return;
		
		try {
			connection.commit();
		} catch ( SQLException e ) {}
		
	}

	/**
	 * rollback 한다.
	 *
	 */
	public void rollback() {

		if( connection == null ) return;
		
		try {
			connection.rollback();
		} catch ( SQLException e ) {}

	}
	
}
